package com.companyName.sample.common.base;

import com.companyName.sample.common.bean.ResponseData;
import com.companyName.sample.common.constant.CommConstants;
import com.companyName.sample.common.constant.ResponseMsg;
import com.companyName.sample.common.exception.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public abstract class CommBaseController {

	private static final Logger logger = LoggerFactory.getLogger(CommBaseController.class);

	/**
	 *  失败的请求返回，封装成ResponseData对象
	 */
	public ResponseData<Object> baseFailureResponse(int code, Object... result) {
		if (result.length == 0) {
			return new ResponseData(code, "");
		} else if (result.length == 1) {
			return new ResponseData(code, result[0]);
		} else {
			return responseData(code, result);
		}
	}
	/**
	 *   封装 ResponseData对象，把参数封装到map中
	 */
	public ResponseData<Object> responseData(int code, Object... keyValuePairs) {
		Map<String, Object> map = new HashMap<String, Object>();
		for (int i = 0; i < keyValuePairs.length; i += 2) {
			map.put((String) keyValuePairs[i], keyValuePairs[i+1]);
		}
		return new ResponseData(code, map);
	}

	/**
	 *  成功的请求返回，封装成ResponseData对象
	 */
	public ResponseData<Object> baseSuccessResponse(Object... result) {
		return baseFailureResponse(ResponseMsg.SUCCESS.getCode(), result);
	}


	public String requestInfo(HttpServletRequest httpRequest) {
		String qs = httpRequest.getQueryString();
		return String.format("%s %s%s%s",
				httpRequest.getMethod(),
				httpRequest.getRequestURL().toString(),
				(StringUtils.isEmpty(qs) ? "" : "?"),
				qs == null ? "" : qs);
	}


	/**
	 *  成功的请求返回，封装成HashMap对象
	 */
	public Map<String, Object> respSuccess(Object data) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("status", ResponseMsg.SUCCESS.getCode());
		model.put("msg", "成功");
		model.put("data", data);
		return model;
	}

	/**
	 *  失败的请求返回，封装成HashMap对象
	 */
	public Map<String, Object> respException() {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("status", ResponseMsg.SUCCESS.getCode());
		model.put("msg", "系统异常");
		return model;
	}

	/**
	 *  获取request的参数并返回Map
	 */
	@SuppressWarnings({"rawtypes", "unchecked"})
	public Map getParameterMap(HttpServletRequest request) {

		// 参数Map
		Map properties = request.getParameterMap();
		// 返回值Map
		Map returnMap = new HashMap();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if (null == valueObj) {
				value = "";
			} else if (valueObj instanceof String[]) {
				String[] values = (String[]) valueObj;
				for (int i = 0; i < values.length; i++) {
					value = values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
			} else {
				value = valueObj.toString();
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}

	/**
	 *  获取User的Pid
	 */
	public Long getPid(HttpServletRequest httpRequest) throws UnauthorizedException {
		return getPid(httpRequest, true);
	}

	/**
	 *  获取User的Pid
	 */
	public Long getPid(HttpServletRequest httpRequest, boolean required) throws UnauthorizedException {
		String pid = httpRequest.getHeader(CommConstants.ReqParamName.Pid);
		if (pid == null) {
			logger.warn("null pid");
			if (required) {
				throw new UnauthorizedException();
			}
			return null;
		}
		return Long.valueOf(pid);
	}

	/**
	 * 是否授权
	 */
	public boolean isAuthorized(HttpServletRequest httpRequest) {
		return httpRequest.getParameter(CommConstants.ReqParamName.Pid) != null;
	}
}
